<template>
	<view>
		<uni-search-bar @input="handleInput" cancelButton="none" @focus="showSearchList=true"
			@confirm="confirm"></uni-search-bar>
		<view class="ul" v-show="showSearchList">
			<view class="li" v-for="(v, i) in searchList" :key="i" @click="confirm({ value: v })">
				<text>{{ v }}</text>
				<text @click.stop="deleteSearchListByIndex(i)">X</text>
			</view>
		</view>
		<view class="ul" v-show="!showSearchList">
			<view class="li" v-for="(v, i) in list" :key="i" @click="toDetail(v)">
				{{ v.desc }}
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				showSearchList: false,
				searchList: uni.getStorageSync("searchList") || [],
				timer: null,
				list: []
			};
		},
		watch: {
			searchList(newValue) {
				uni.setStorageSync("searchList", newValue)
			}
		},
		methods: {
			toDetail(v) {
				// 2. 头部推入数组
				this.searchList.unshift(v.desc);
				// 3. 去重复
				this.searchList = [...new Set(this.searchList)];
				// 跳转
				uni.navigateTo({
					url: '/pages/detail/detail?id=' + v.id
				})
			},
			// 搜索函数
			async handleSearch(value) {
				if (value.trim() === "") {
					this.showSearchList = true
					return;
				}
				const [error, resp] = await uni.request({
					url: 'http://localhost:3000/list',
					data: {
						q: value,
						_page: 1
					}
				});
				this.showSearchList = false
				this.list = resp.data;
			},
			// 实时输入事件
			handleInput(value) {
				// 搜索节流
				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					this.handleSearch(value)
				}, 400)
			},
			// 确定搜索
			confirm(e) {
				/********************** 记录历史搜索 *********************/
				// 1. 获取搜索的值
				const {
					value
				} = e;
				// 2. 头部推入数组
				this.searchList.unshift(value);
				// 3. 去重复
				this.searchList = [...new Set(this.searchList)];
				// 4. 进入搜索结果也
				uni.navigateTo({
					url: '/pages/searchResult/searchResult?q=' + value
				})

			},
			// 历史记录删除
			deleteSearchListByIndex(i) {
				this.searchList.splice(i, 1)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.ul {
		padding: 20rpx;

		.li {
			border-bottom: 2rpx solid #ccc;
			line-height: 60rpx;
			padding-left: 1rpx;
			display: flex;
			justify-content: space-between;
		}
	}
</style>